package cn.com.hhrcw.web;

import cn.com.hhrcw.entity.EnNews;
import cn.com.hhrcw.entity.SysUser;
import cn.com.hhrcw.mapstruct.EnNewsConvert;
import cn.com.hhrcw.params.EnNewsParams;
import cn.com.hhrcw.service.IEnNewsService;
import cn.com.hhrcw.utils.SubjectUtils;
import cn.com.hhrcw.vo.EnNewsVO;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.base.entity.AttributesValueParams;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;
import java.util.function.Function;

/**
* 消息记录
*
* @author jiangdong
* @since 2020-10-29
*/
@RestController
@Slf4j
@RequestMapping("/personal/v1/enNews")
@Api(tags = "消息记录")
@Validated
public class EnNewsController extends JeecgController<EnNews, IEnNewsService> {

    @Autowired
    private IEnNewsService enNewsService;

    @Autowired
    private EnNewsConvert enNewsConvert;


    /**
    * 个人消息列表
    *
    * @param params 请求参数
    * @return
    */
    @GetMapping(value = "/list")
    @AutoLog("消息记录-分页列表查询")
    @ApiOperation(value = "分页列表查询", notes = "分页列表查询")
    public Result<Page<EnNewsVO>> list(EnNewsParams params, HttpServletRequest request) {
        QueryWrapper<EnNews> queryWrapper = QueryGenerator.initQueryWrapper(enNewsConvert.toEntity(params), request.getParameterMap());
        queryWrapper.eq("del_flag", false);
        if (StringUtils.isBlank(params.getField())) {
            queryWrapper.orderByDesc("create_time");
        } else {
            queryWrapper.orderBy(true, params.getSort(), toUnderlineName(params.getField()));
        }
        SysUser sysUser = (SysUser) SubjectUtils.getSubject();
        queryWrapper.eq("receive_id", sysUser.getId()).eq("receive_type",0);
        IPage<EnNews> page = enNewsService.page(params.page(), queryWrapper);
        //分页结果转换器
        Function<EnNews, EnNewsVO> fun = enNews -> enNewsConvert.toVO(enNews);

        return Result.ok((Page)page.convert(fun));
    }
    /**
     * 个人消息未读数量
     *
     * @param params 请求参数
     * @return
     */
    @PostMapping(value = "/count")
    public Result<?> count(EnNewsParams params, HttpServletRequest request) {
        QueryWrapper<EnNews> queryWrapper = QueryGenerator.initQueryWrapper(enNewsConvert.toEntity(params), request.getParameterMap());
        queryWrapper.eq("del_flag", false);
        if (StringUtils.isBlank(params.getField())) {
            queryWrapper.orderByDesc("create_time");
        } else {
            queryWrapper.orderBy(true, params.getSort(), toUnderlineName(params.getField()));
        }
        SysUser sysUser = (SysUser) SubjectUtils.getSubject();
        queryWrapper.eq("receive_id", sysUser.getId());
        queryWrapper.eq("read_flag",0).eq("receive_type",0);
        int count = enNewsService.count(queryWrapper);
        //分页结果转换器
        return Result.ok(count);
    }

    /**
    * 根据id查询
    *
    * @param id 数据id
    * @return
    */
    @GetMapping(value = "/queryById")
    @ApiOperation(value = "根据id查询", notes = "根据id查询")
    public Result<EnNewsVO> queryById(String id) {
        EnNews enNews = enNewsService
            .lambdaQuery()
            .eq(EnNews::getId,id)
            .eq(EnNews::getDelFlag,false)
            .one();
        if(enNews == null){
            throw new JeecgBootException("数据不存在");
        }
        enNews.setReadFlag(1);
        enNewsService.updateById(enNews);
        return Result.ok(enNewsConvert.toVO(enNews));
    }

    /**
    * 添加
    *
    * @param params 请求参数
    * @return
    */
    @PostMapping(value = "/add")
    @AutoLog("消息记录-添加")
    @ApiOperation(value = "添加", notes = "添加")
    @RequiresPermissions("enNews:add")
    public Result<?> add(@RequestBody @Valid EnNewsParams params) {

        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        EnNews enNews = enNewsConvert.toEntity(params);
        enNews.setCreateBy(sysUser.getId());
        enNews.setCreateTime(DateUtil.date());
        enNews.setDelFlag(false);

        boolean saved = enNewsService.save(enNews);
        return saved ? Result.ok() : Result.error("添加失败");
    }

    /**
    * 编辑
    *
    * @param params 请求参数
    * @return
    */
    @PostMapping(value = "/edit")
    @AutoLog("消息记录-编辑")
    @ApiOperation(value = "编辑", notes = "编辑")
    @RequiresPermissions("enNews:edit")
    public Result<?> edit(@RequestBody @Valid EnNewsParams params) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        EnNews enNews = enNewsConvert.toEntity(params);
        enNews.setUpdateBy(sysUser.getId());
        enNews.setUpdateTime(DateUtil.date());

        boolean updated = enNewsService.updateById(enNews);
        return updated ? Result.ok() : Result.error("编辑失败");
    }


    /**
    * 批量删除
    *
    * @param id 数据id
    * @return
    */
    @GetMapping(value = "/delete")
    @AutoLog("消息记录-批量删除")
    @ApiOperation(value = "批量删除", notes = "批量删除")
    @RequiresPermissions("enNews:delete")
    public Result delete(String[] id) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        LambdaUpdateWrapper<EnNews> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.in(EnNews::getId, id)
            .set(EnNews::getDelFlag, true)
            .set(EnNews::getUpdateBy, sysUser.getUsername())
            .set(EnNews::getUpdateTime, DateUtil.date());

        boolean deleted = enNewsService.update(updateWrapper);
        return deleted ? Result.ok() : Result.error("删除失败");
    }

    /**
    * 属性值是否重复
    *
    * @return
    */
    @Override
    @GetMapping("/propertyRepeat")
    @ApiOperation(value = "属性值是否重复", notes = "属性值是否重复")
    public Result propertyIsRepeat(@Valid AttributesValueParams params) {
        return super.propertyIsRepeat(params);
    }

    /**
    * 导出excel
    *
    * @param request
    * @param params
    */
    @SneakyThrows
    @GetMapping(value = "/exportXls")
    @ApiOperation(value = "导出excel", notes = "导出excel")
    public Result exportXls(HttpServletRequest request, EnNewsParams params) {
        EnNews enNews = enNewsConvert.toEntity(params);
        enNews.setDelFlag(false);
        QueryWrapper<EnNews> queryWrapper = QueryGenerator.initQueryWrapper(enNews, request.getParameterMap());
        List<EnNews> data = enNewsService.list(queryWrapper);
        ExportParams exportParams = new ExportParams("消息记录", "消息记录");
        String url = super.exportXls(exportParams, EnNewsVO.class,enNewsConvert.toVO(data));
        return Result.ok((Object) url);
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @PostMapping(value = "/importExcel")
    @ApiOperation(value = "通过excel导入数据", notes = "通过excel导入数据")
        public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, EnNews.class);
    }

}
